<script setup>
import { ref, watch, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 这里假设你已经按照后端接口规范定义好了班级相关的 API，以下是示例引入，需根据实际情况调整
import {
  queryClazzPageApi,
  addClazzApi,
  queryInfoApi,
  updateClazzApi,
  deleteClazzApi,
} from "@/api/clazz";
import { queryAllApi as queryAllDeptApi } from "@/api/dept";

//导入员工数据
import { queryAllEmpListApi } from "@/api/emp";

//声明token
const token = ref("");
// 班级状态列表数据，可根据实际情况调整
const statusList = ref([
  { label: "未开班", value: "0" },
  { label: "在读", value: "1" },
  { label: "已结课", value: "2" },
]);

// 班级列表数据
const clazzList = ref([]);

// 存储搜索班级的条件，包括班级名称、开始日期和结束日期
const searchClazz = ref({
  name: "",
  beginDate: "",
  endDate: "",
});

// 监听 searchClazz 中的 date 属性，如果 date 长度为 2，将其拆分为开始日期和结束日期
watch(
  () => searchClazz.value.date,
  (newValue, oldValue) => {
    if (newValue.length === 2) {
      searchClazz.value.beginDate = newValue[0];
      searchClazz.value.endDate = newValue[1];
    } else {
      searchClazz.value.beginDate = "";
      searchClazz.value.endDate = "";
    }
  }
);

// 员工列表信息
const employee = ref([]);

onMounted(async () => {
  await handleSearch();
  //加载员工数据，将员工数据里的name跟id封装
  const resultEmpList = await queryAllEmpListApi();

  if (resultEmpList.code === 200) {
    employee.value = resultEmpList.data;
    // console.log(employee.value);
  } else {
    ElMessage.error("获取员工列表数据失败：" + resultEmpList.msg);
  }
});

//加载localStorage存储的员工登录信息
const loginUser = localStorage.getItem("user");
if (loginUser) {
  token.value = JSON.parse(loginUser).token;
}

// 查询班级信息的函数
const handleSearch = async () => {
  try {
    const result = await queryClazzPageApi(
      searchClazz.value.name,
      searchClazz.value.beginDate,
      searchClazz.value.endDate,
      currentPage.value,
      pageSize.value
    );
    if (result.code === 200) {
      clazzList.value = result.data.rows;
      console.log(clazzList.value);

      total.value = result.data.total;
    } else {
      ElMessage.error("查询班级列表失败：" + result.msg);
    }
  } catch (error) {
    ElMessage.error("查询班级列表时发生错误，请稍后重试");
    console.error(error);
  }
};

// 重置搜索条件并重新查询班级信息
const handleReset = () => {
  // 清空表单
  searchClazz.value = {
    name: "",
    beginDate: "",
    endDate: "",
  };
  handleSearch();
};

// 分页配置
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 分页处理函数，当页大小改变时调用
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

// 分页处理函数，当当前页码改变时调用
const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};

// 编辑班级信息的操作处理函数
const handleEdit = async (id) => {
  try {
    const result = await queryInfoApi(id);
    if (result.code === 200) {
      dialogVisible.value = true;
      dialogTitle.value = "修改班级";
      clazz.value = result.data;
    } else {
      ElMessage.error("获取班级详情失败：" + result.msg);
    }
  } catch (error) {
    ElMessage.error("获取班级详情时发生错误，请稍后重试");
    console.error(error);
  }
};

// 删除单个班级的操作处理函数
const handleDelete = async (id) => {
  ElMessageBox.confirm("确定删除该班级吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const result = await deleteClazzApi(id);
      console.log(result);

      if (result.code === 200) {
        ElMessage.success("删除班级成功");
        await handleSearch();
      } else {
        ElMessage.error("删除班级失败：" + result.msg);
      }
    } catch (error) {
      ElMessage.error("删除班级时发生错误，请稍后重试");
      console.error(error);
    }
  });
};

// 新增班级信息的操作处理函数
const addClazz = () => {
  dialogVisible.value = true;
  dialogTitle.value = "新增班级";
  clazz.value = {
    name: "",
    room: "",
    beginDate: "",
    endDate: "",
    masterId: "",
    subject: "",
    createTime: "",
    updateTime: "",
    masterName: "",
    status: "",
  };
  // 重置表单
  clazzFormRef.value.resetFields();
};

//学科, 1:java, 2:前端, 3:大数据, 4:Python, 5:Go, 6: 嵌入式'
const subjectList = ref([
  { name: "java", id: 1 },
  { name: "前端", id: 2 },
  { name: "大数据", id: 3 },
  { name: "Python", id: 4 },
  { name: "Go", id: 5 },
  { name: "嵌入式", id: 6 },
]);

// 新增/修改表单的引用
const clazzFormRef = ref(null);
// 存储当前操作的班级信息（新增或修改）
const clazz = ref({
  name: "",
  room: "",
  beginDate: "",
  endDate: "",
  masterId: "",
  subject: "",
  createTime: "",
  updateTime: "",
  masterName: "",
  status: "",
});

// 表单校验规则，确保输入的数据符合要求
const rules = ref({
  name: [
    { required: true, message: "请输入班级名称", trigger: "blur" },
    {
      min: 1,
      max: 50,
      message: "班级名称长度应在 1 到 50 个字符之间",
      trigger: "blur",
    },
  ],
  beginDate: [
    { required: true, message: "请输入开课时间", trigger: "blur" },
    {
      type: "date",
      message: "请输入正确的日期格式（YYYY-MM-DD）",
      trigger: "blur",
    },
  ],
  endDate: [
    { required: true, message: "请输入结课时间", trigger: "blur" },
    {
      type: "date",
      message: "请输入正确的日期格式（YYYY-MM-DD）",
      trigger: "blur",
    },
  ],
  masterId: [{ required: true, message: "请选择班主任", trigger: "change" }],
  subject: [{ required: true, message: "请选择学科", trigger: "change" }],
  status: [{ required: true, message: "请选择班级状态", trigger: "change" }],
});

// 控制弹窗的显示与隐藏
const dialogVisible = ref(false);
const dialogTitle = ref("新增班级");

// 保存班级信息的操作处理函数
const save = async () => {
  clazzFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let result;
        if (clazz.value.id) {
          // 存在 ID，执行修改操作
          result = await updateClazzApi(clazz.value);
        } else {
          // 不存在 ID，执行新增操作
          result = await addClazzApi(clazz.value);
        }
        if (result.code === 200) {
          ElMessage.success("保存班级信息成功");
          dialogVisible.value = false;
          await handleSearch();
        } else {
          ElMessage.error("保存班级信息失败：" + result.msg);
        }
      } catch (error) {
        ElMessage.error("保存班级信息时发生错误，请稍后重试");
        console.error(error);
      }
    }
  });
};

// 存储选中的班级 ID 列表，用于批量操作
const selectedIds = ref([]);

// 处理表格中复选框选择变化的函数，更新 selectedIds 数组
function handleSelectionChange(selection) {
  const ids = selection.map((item) => item.id);
  selectedIds.value = ids;
}
</script>

<template>
  <h1>班级管理</h1>
  <br />
  <el-form
    ref="clazzFormRef"
    :inline="true"
    :model="searchClazz"
    class="demo-form-inline"
  >
    <el-form-item label="班级名称">
      <el-input
        size="large"
        v-model="searchClazz.name"
        placeholder="请输入班级名称"
      ></el-input>
    </el-form-item>

    <el-form-item label="开课时间至结课时间">
      <el-date-picker
        v-model="searchClazz.date"
        type="daterange"
        range-separator="至"
        start-placeholder="开课时间"
        end-placeholder="结课时间"
        value-format="YYYY-MM-DD"
      ></el-date-picker>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>

  <el-button type="primary" @click="addClazz"> + 新增班级</el-button>
  <br /><br />

  <!-- 表格 -->
  <el-table
    :data="clazzList"
    border
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column
      type="selection"
      width="55"
      align="center"
    ></el-table-column>
    <!-- 序号 -->
    <el-table-column
      type="index"
      label="序号"
      width="80"
      align="center"
    ></el-table-column>

    <el-table-column
      prop="name"
      label="班级名称"
      width="120"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="room"
      label="班级教室"
      width="120"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="masterName"
      label="班主任"
      width="120"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="beginDate"
      label="开课时间"
      width="180"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="endDate"
      label="结课时间"
      width="180"
      align="center"
    ></el-table-column>

    <el-table-column
      prop="status"
      label="班级状态"
      width="120"
      align="center"
    ></el-table-column>
    <!-- 最后修改时间 -->
    <el-table-column
      prop="updateTime"
      label="最后修改时间"
      width="180"
      align="center"
    ></el-table-column>
    <el-table-column label="操作" fixed="right" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.row.id)"
          >编辑</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.row.id)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <br />

  <!-- 分页 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[10, 20, 30, 40]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  >
  </el-pagination>

  <!-- 新增/修改班级的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="clazzFormRef"
      :model="clazz"
      :rules="rules"
      label-width="80px"
    >
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="班级名称" prop="name">
            <el-input
              v-model="clazz.name"
              placeholder="请输入班级名称，1-50个字"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="班级教室" prop="room">
            <el-input
              v-model="clazz.room"
              placeholder="请输入班级教室"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开课时间" prop="beginDate">
            <el-date-picker
              v-model="clazz.beginDate"
              type="date"
              style="width: 100%"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="结课时间" prop="endDate">
            <el-date-picker
              v-model="clazz.endDate"
              type="date"
              style="width: 100%"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="班主任" prop="masterId">
            <el-select
              v-model="clazz.masterId"
              placeholder="请选择班主任"
              style="width: 100%"
            >
              <el-option
                v-for="empList in employee"
                :key="empList.id"
                :label="empList.name"
                :value="empList.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="学科" prop="subject">
            <el-select
              v-model="clazz.subject"
              placeholder="请选择学科"
              style="width: 100%"
            >
              <!-- 假设这里有学科列表数据，示例如下 -->
              <el-option
                v-for="subjectOption in subjectList"
                :key="subjectOption.id"
                :label="subjectOption.name"
                :value="subjectOption.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 底部按钮 -->
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar {
  height: 40px;
}
/* 其他已有样式保持不变 */

.el-dialog.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.el-dialog.dialog-footer el-button {
  display: inline-block;
}
</style>
